<?php

class EwayController extends CustomControllerBase {
	
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		// Set page name
		$this->setPageName ( 'eway_handler' );
	
	}
	
	/**
	 * The "index" action is the default action for all controllers -- the
	 * landing page of the site.
	 *
	 * @return void
	 *
	 */
	public function indexAction() {
		
		$config = $this->settingsDataService->getEwaySettings ( $this->ownerId );
		$url = $this->getApplicationUrl () . "Product/orderFail";
		if (! empty ( $config ['customerId'] ) && ! empty ( $config ['username'] ) && isset ( $config ['enable'] ) && $config ['enable'] == true) {
			$params = array ("CustomerID" => $config ['customerId'], "UserName" => $config ['username'], "AccessPaymentCode" => $_REQUEST ['AccessPaymentCode'] );
			$params = http_build_query ( $params );
			$postURL = "https://payment.ewaygateway.com/Result/?$params";
			
			$ch = curl_init ();
			curl_setopt ( $ch, CURLOPT_URL, $postURL );
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
			curl_setopt ( $ch, CURLOPT_HEADER, 1 );
			curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
			if (defined ( 'CURL_PROXY_REQUIRED' ) && CURL_PROXY_REQUIRED == 'True') {
				$proxy_tunnel_flag = (defined ( 'CURL_PROXY_TUNNEL_FLAG' ) && strtoupper ( CURL_PROXY_TUNNEL_FLAG ) == 'FALSE') ? false : true;
				curl_setopt ( $ch, CURLOPT_HTTPPROXYTUNNEL, $proxy_tunnel_flag );
				curl_setopt ( $ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
				curl_setopt ( $ch, CURLOPT_PROXY, CURL_PROXY_SERVER_DETAILS );
			}
			$response = curl_exec ( $ch );
			$responsecode = $this->_fetchEwayData ( $response, '<responsecode>', '</responsecode>' );
			
			// Order ID
			$orderID = $this->_fetchEwayData ( $response, '<merchantreference>', '</merchantreference>' );
			$trxnStatus = $this->_fetchEwayData ( $response, '<trxnstatus>', '</trxnstatus>' );
			try {
				// Success
				if ($trxnStatus == "true") {
					// Get order
					$customerOrderDataService = new CustomerOrderDataService ();
					$arrElement = array ();
					$arrElement ['id'] = intval ( $orderID );
					$arrElement ['payment_method'] = PAYMENT_EWAY;
					$results = $customerOrderDataService->getItems ( $arrElement );
					if (count ( $results ) > 0 && ! empty ( $results [0] )) {
						// Update order status
						$customerOrder = $results [0];
						$customerOrder->last_modified = date ( "Y-m-d H:i:s" );
						$customerOrder->orders_status = ORDER_STATUS_PROCESSING;
						$customerOrderDataService->update ( $customerOrder );
						
						// Add order history
						$orderStatusHistoryDataService = new OrderStatusHistoryDataService ();
						$orderHistory = $orderStatusHistoryDataService->beforeCreate ();
						$orderHistory->orders_id = $customerOrder->id;
						$orderHistory->date_added = date ( "Y-m-d H:i:s" );
						$orderHistory->comments = "";
						$orderHistory->orders_status = ORDER_STATUS_PROCESSING;
						$orderStatusHistoryDataService->create ( $orderHistory );
						
						// Empty cart
						$userCustomerBasketDataService = new UserCustomerBasketDataService ();
						$userCustomerBasketDataService->removeCart ( $customerOrder->customers_id, NULL );
						
						$url = $this->getApplicationUrl () . "Product/orderSuccess";
					}
				} else {
					// Add order history
					$orderStatusHistoryDataService = new OrderStatusHistoryDataService ();
					$orderHistory = $orderStatusHistoryDataService->beforeCreate ();
					$orderHistory->orders_id = intval ( $orderID );
					$orderHistory->date_added = date ( "Y-m-d H:i:s" );
					$orderHistory->comments = "";
					$orderHistory->orders_status = ORDER_STATUS_PENDING;
					$orderStatusHistoryDataService->create ( $orderHistory );
				}
			} catch ( Exception $e ) {
			
			}
		}
		
		CommonUtils::redirect ( $url );
	}
	
	/**
	 * Fetch response from Eway
	 * @param string $string
	 * @param string $start_tag
	 * @param string $end_tag
	 * @return string $fetch_data
	 */
	protected function _fetchEwayData($string, $start_tag, $end_tag) {
		$position = stripos ( $string, $start_tag );
		$str = substr ( $string, $position );
		$str_second = substr ( $str, strlen ( $start_tag ) );
		$second_positon = stripos ( $str_second, $end_tag );
		$str_third = substr ( $str_second, 0, $second_positon );
		$fetch_data = trim ( $str_third );
		return $fetch_data;
	}
}
